<?php
/**
 * @version $Id: view.html.php 1212 2010-05-26 20:13:35Z elkuku $
 * @package    EasyCreator
 * @subpackage Views
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath (elkuku) {@link http://www.nik-it.de NiK-IT.de}
 * @author     Created on 07-Mar-2008
 * @license    GNU/GPL, see JROOT/LICENSE.php
 */

//-- No direct access
defined('_JEXEC') or die('=;)');

jimport( 'joomla.application.component.view');

/**
 * HTML View class for the EasyCreator Component
 *
 * @package EasyCreator
 * @subpackage Views
 */
class EasyCreatorViewLanguages extends JView
{
    function display($tpl = null)
    {
        ecrLoadHelper('languagehelper');

        $ecr_project = JRequest::getCmd('ecr_project');
        $task = JRequest::getCmd('task');

        $this->hideLangs = JRequest::getVar('hide_langs', array());
        $this->scope = JRequest::getCmd('scope');
        $this->_showCore = JRequest::getCmd('showCore');

        $this->project = EasyProjectHelper::getProject($ecr_project);

        if( ! $this->project)
        {
            JError::raiseWarning(100, JText::sprintf('Unable to load the project %s', $ecr_project));
            ecrHTML::easyFormEnd();

            return;
        }

        if( ! $this->scope)
        {
            $this->scope = 'site';

            if($this->project->type == 'plugin')
            {
                //-- todo special treatment for plugins
                $this->scope = 'admin';
            }
        }

        //--Draw h1 header
        ecrHTML::header(JText::_('Languages'), $this->project);

        if( ! count($this->project->langs))
        {
            $this->easyLanguage = false;
        }
        else
        {
            ecrLoadHelper('language');
            $this->easyLanguage = new EasyLanguage($this->project, $this->scope, $this->hideLangs);

            if(JRequest::getCmd('tmpl') != 'component')
            {

                //--draw selector
                echo $this->displayBar($task);
            }
        }

        /**
         * Handle the 'task' value -> call a function
         * Softly exit on undefined
         */
        if(in_array($task, get_class_methods($this)))
        {
            //--Execute the task
            $this->$task();
        }
        else if($task)
        {
            echo 'UNDEFINED: '.$task.'<br />';
            ecrHTML::easyFormEnd();

            return;
        }

        parent::display($tpl);

        ecrHTML::easyFormEnd();
    }// function

    private function convert()
    {
        $this->selected_file = JRequest::getVar('selected_file');

        $this->options = JArrayHelper::toObject(JRequest::getVar('options', array()), 'JObject');

        ecrLoadHelper('languageconverter');

        $this->converter = new ECRLanguageConverter($this->options);

        if($this->options->get('add_prefix')) $this->converter->prefix = strtoupper($this->project->comName);

        $files = array();

        foreach($this->project->copies as $copy)
        {
            switch($this->scope)
            {
                case 'admin':
                case 'menu':
                    if(strpos($copy, JPATH_ADMINISTRATOR) === false)
                    {
                        continue;
                    }
                    break;

                case 'site':
                    $pos = strpos($copy, JPATH_ADMINISTRATOR);

                    if(strpos($copy, JPATH_ADMINISTRATOR) === 0)
                    {
                        continue 2;
                    }
                    break;
                default:
                    ;
                    break;
            }//switch

            $files = array_merge(JFolder::files($copy, '\.php$', true, true), $files);
        }//foreach

        $fileList = array();
        $badDefinitions = array();

        foreach($files as $fileName)
        {
            $fileList[$fileName] = 0;
            $definitions = EasyLanguage::getKeys($fileName);

            foreach($definitions as $definition => $file)
            {
                if( ! $this->converter->isCleanKey($definition))
                {
                    $fileList[$file] ++;
                    $badDefinitions[] = $definition;

                }
            }//foreach
        }//foreach

        $this->assignRef('fileList', $fileList);
        $this->assignRef('badDefinitions', $badDefinitions);

        $this->menuBoxes = array();

        $html = '';
        $html .= '<div class="ecr_menu_box" style="margin-left: 0.3em;">';
        $html .= JText::_('File');
        $html .= '<select onchange="submitform(\'convert\');" name="selected_file">';
        $html .= '<option value="">'.JText::_('Select').'</option>';

        foreach($this->fileList as $file => $errors)
        {
            if( ! $errors) continue;

            $s = str_replace(JPATH_ROOT.DS, '', $file);
            $selected =($s == $this->selected_file) ? 'selected="selected"' : '';
            $html .= '<option '.$selected.' value="'.$s.'">'.$s.' ('.$errors.')</option>';
        }//foreach

        $html .= '</select>';
        $html .= '</div>';

        $this->menuBoxes['file'] = $html;

        $origCode = JFile::read(JPATH_ROOT.DS.$this->selected_file);
        $this->fileErrors = $this->converter->findPHPErrors($origCode, $this->badDefinitions);


        $html = '';
        $this->diff = '';

        if(count($this->fileErrors))
        {
        $html .= '<div style="border: 1px dashed orange; padding: 0.3em; margin-top: 1em; margin-bottom: 1em; background-color: #fff;">';
        $html .= '<b style="color: red;">'.JText::_('Errors').'</b>'.BR;
        $html .= JText::_('Please select the errors you wish to correct').BR;

        $newCode = $origCode;

        foreach($this->fileErrors as $errorKey => $errorJText)
        {
            //-- Draw a hidden field
            $s = htmlspecialchars(str_replace('"', '__QQ__', $errorJText));
            $s1 = htmlspecialchars(str_replace('"', '__QQ__', $errorKey));
            $html .= '<input type="hidden" name="file_errors['.$s1.']" value="'.$s.'" />';
            $html .= '<input type="checkbox" checked="checked" id="error_'.$s1.'" name="selected_errors['.$s1.']" /><label for="error_'.$s1.'">'.$s1.'</label>'.BR;

            $newJText = str_replace($errorKey, $this->converter->cleanKey($errorKey), $errorJText);
            $newCode = str_replace($errorJText, $newJText, $newCode);
        }//foreach

        $html .= '</div>';
        $this->diff = $this->converter->getDiffTable($origCode, $newCode, $this->options->get('php_show_all'));
        }

        $this->menuBoxes['file_errors'] = $html;

        $this->setLayout('convert');;
    }//function

    /*
     * Task methods
     */

    function languages()
    {
    }//function

    private function translations()
    {
        if( $this->project->langs)
        {
            $this->prepareTranslation();
            $this->default_file = $this->easyLanguage->getDefaultFile();
        }

        $this->setLayout('translations');
    }//function

    function searchfiles()
    {
        $this->prepareTranslation();
        $this->setLayout('searchfiles');;
    }

    private function prepareTranslation()
    {
        switch($this->scope)
        {
            case 'admin':
            case 'menu':
                $workPath = JPATH_ADMINISTRATOR;
                break;
            case 'site':
                $workPath = JPATH_SITE;
                break;
            default:
                JError::raiseWarning(100, 'wrong scope..');
                return;
                break;
        }//switch

        if($this->project->type == 'plugin')
        {
            //-- @todo apecial treatment for plugins
            $workPath = JPATH_ADMINISTRATOR;
        }

        $this->showCore = JRequest::getCmd('showCore');

        $this->easyLanguage->_readStrings($workPath);

        if( $this->showCore )
        {
            $this->easyLanguage->_readStrings($workPath, true);
        }

        $this->languages = $this->easyLanguage->getLanguages();
        $this->hideLangs = $this->easyLanguage->getHideLangs();
        $this->definitions = $this->easyLanguage->getDefinitions();
        $this->strings = $this->easyLanguage->getStrings();
        $this->coreStrings = $this->easyLanguage->getCoreStrings();
    }

    function langcorrectorder()
    {
        $sel_language = JRequest::getCmd('sel_language');
        if($sel_language == 'en-GB')
        {
            $sel_language = '';
        }

        $default_language = array();
        $translated_language = array();

        if($sel_language)
        {
            $fileNameDef = $this->easyLanguage->getFileName('en-GB', $this->scope, $this->project);
            $fileName = $this->easyLanguage->getFileName($sel_language, $this->scope, $this->project);

            $default_language = $this->easyLanguage->parseFile($fileNameDef);
            $translated_language = $this->easyLanguage->parseFile($fileName);
            $corrected_language = $this->easyLanguage->correctTranslation( $default_language, $translated_language);
        }

        $this->assignRef('default_language', $default_language);
        $this->assignRef('translated_language', $translated_language);
        $this->assignRef('corrected_language', $corrected_language);

        $this->assignRef('sel_language', $sel_language);

        $this->setLayout('ordertranslation');
    }//function

    function langcorrectdeforder()
    {
        $fileName = JPATH_ROOT;

        $fileName = $this->easyLanguage->getFileName('en-GB', $this->scope, $this->project);
        $default_language = $this->easyLanguage->parseFile($fileName);

        $this->assignRef('default_language', $default_language);

        $this->setLayout('orderdefault');
    }//function

    function translate()
    {
        $trans_lang = JRequest::getCmd('trans_lang');
        $trans_key = JRequest::getString('trans_key');

        if($trans_lang != 'en-GB')
        {
            $this->trans_default = $this->easyLanguage->getTranslation('en-GB', $trans_key);
        }

        $this->translation = $this->easyLanguage->getTranslation($trans_lang, $trans_key);

        $this->assignRef('trans_lang', $trans_lang);
        $this->assignRef('trans_key', $trans_key);

        $this->setLayout('translator');
    }//function

    function show_versions()
    {
        $this->show_version();
    }//function

    function show_version()
    {
        $sel_language = JRequest::getCmd('sel_language', '');
        $selected_version = JRequest::getInt('selected_version', 0);

        if($sel_language)
        {
            $versions = $this->easyLanguage->getVersions($sel_language);
            $this->assignRef('versions', $versions);
        }

        $this->assignRef('sel_language', $sel_language);
        $this->assignRef('selected_version', $selected_version);

        $this->setLayout('versions');
    }//function

    function language_check()
    {
        if($this->easyLanguage)
        {
            $this->languages = $this->easyLanguage->getLanguages();
        }

        $this->setLayout('check');
    }//function

    private function displayBar($task)
    {
        $task = JRequest::getCmd('task');
        $sel_language = JRequest::getCmd('sel_language');
        $this->sel_language = $sel_language;

        $imgBase = JURI::root().'administrator/components/com_easycreator/assets/images/ico/';

        //--Get component parameters
        $ecr_help = JComponentHelper::getParams('com_easycreator')->get('ecr_help');

        $subTasks = array(
        array('title' => JText::_('Setup')
        , 'description' => JText::_('DESC LANG SETUP')
        , 'icon' => 'apply'
        , 'tasks' => array('languages')
        )
        , array('title'=> JText::_('Translations')
        , 'description' => JText::_('DESC LANG TRANSLATIONS')
        , 'icon' => 'ecr_language'
        , 'tasks' => array('translations', 'dotranslate')
        )
        , array('title'=> JText::_('Files and Menus')
        , 'description' => JText::_('DESC LANG SEARCHFILES')
        , 'icon' => 'ecr_language'
        , 'tasks' => array('searchfiles')
        )
        , array('title' => JText::_('Default file order')
        , 'description' => JText::_('DESC LANG ORDER DEFAULT')
        , 'icon' => 'text'
        , 'tasks' => array('langcorrectdeforder', 'save_deflang_corrected')
        )
        , array('title' => JText::_('Translation order')
        , 'description' => JText::_('DESC LANG ORDER TRANS')
        , 'icon' => 'text'
        , 'tasks' => array('langcorrectorder', 'save_lang_corrected')
        )
        , array('title' => JText::_('Versions')
        , 'description' => JText::_('DESC LANG VERSIONS')
        , 'icon' =>'sig'
        , 'tasks' => array('show_versions', 'show_version')
        )
        , array('title' => JText::_('Convert')
        , 'description' => JText::_('DESC LANG VERSIONS')
        , 'icon' =>'rename'
        , 'tasks' => array('convert', 'convert')
        )
        );

        $html = '';
        $htmlDescriptionDivs = '';
        $jsVars = '';
        $jsMorphs = '';
        $jsEvents = '';

        foreach($subTasks as $sTask)
        {
            $selected =(in_array($task, $sTask['tasks'])) ? '_selected' : '';
            $html .= '<span id="btn_'.$sTask['tasks'][0].'" style="margin-left: 0.3em;" class="ecr_button'.$selected.' img icon-16-'.$sTask['icon'].'" onclick="submitbutton(\''.$sTask['tasks'][0].'\');">';
            $html .= $sTask['title'].'</span>';

            if($ecr_help == 'all'
            || $ecr_help == 'some')
            {
                $htmlDescriptionDivs .= '<div class="hidden_div ecr_description" id="desc_'.$sTask['tasks'][0].'">'.$sTask['description'].'</div>';
                $jsVars .= "var desc_".$sTask['tasks'][0]." = $('desc_".$sTask['tasks'][0]."');\n";

                $jsEvents .= "$('btn_".$sTask['tasks'][0]."').addEvents({\n"
                . "'mouseenter': showTaskDesc.bind(desc_".$sTask['tasks'][0]."),\n"
                . "'mouseleave': hideTaskDesc.bind(desc_".$sTask['tasks'][0].")\n"
                . "});\n";
            }
        }//foreach

        $html .= '<div style="clear: both; height: 1em;"></div>';


        //-- Scope selector
        if($this->project->type == 'component'
        && $task != 'languages')
        {
            $html .= '<div class="ecr_menu_box" style="margin-left: 0.3em;">';
            $html .= JText::_('Scope').'&nbsp;';
            $html .= '<select name="scope" onchange="submitbutton(\''.$task.'\');">';

            $html .= '<option value="admin" ';
            $html .=($this->scope == 'admin') ? ' selected="selected"': '';
            $html .= '>';
            $html .= 'Admin</option>';

            $html .= '<option value="site" ';
            $html .=($this->scope == 'site') ? ' selected="selected"' : '';
            $html .= '>';
            $html .= 'Site</option>';

            $html .= '<option value="menu" ';
            $html .=($this->scope == 'menu') ? ' selected="selected"' : '';
            $html .= '>';
            $html .= JText::_('Menu').'</option>';

            $html .= '</select>';
            $html .= '</div>';
        }

        switch($task)
        {
            case 'translations':
            case 'searchfiles':
                if(count($this->project->langs) > 2)
                {
                    $html .= '<div class="ecr_menu_box">';
                    $html .= JText::_('Do NOT show').': ';
                    foreach($this->project->langs as $lang => $scopes)
                    {
                        if($lang == 'en-GB')
                        {
                            //--always show default language
                            continue;
                        }

                        $checked =(in_array($lang, $this->hideLangs)) ? 'checked="checked"' : '';
                        $color =(in_array($lang, $this->hideLangs)) ? 'red' : 'green';
                        $html .= '<input type="checkbox" name="hide_langs[]" id="hide_langs_'.$lang.'" value="'.$lang.'" '.$checked.' onclick="submitbutton(\''.$task.'\');">';
                        $html .= '<label for="hide_langs_'.$lang.'" style="color: '.$color.';">'.$lang.'</label>';
                    }//foreach
                    $html .= '</div>';
                }

                if($task == 'searchfiles')
                {
                    $html .= '<div class="ecr_menu_box">';

                    if($this->_showCore)
                    {
                        $checked = ' checked="checked"';
                        $style = ' style="color: red;"';
                    }
                    else
                    {
                        $checked = '';
                        $style = ' style="color: blue;"';
                    }

                    $html .= '<input type="checkbox" name="showCore" id="showCore" value="show_core" onclick="submitbutton(\'searchfiles\');" '.$checked.'>';
                    $html .= '<label for="showCore" '.$style.'>'.JText::_('Load core language').'</label>';
                    $html .= '<img src="'.$imgBase.'icon-16-info.png" class="hasEasyTip" title="'.JText::_('Load core language').'::'.JText::_('CORELANG_DESC').'" />';
                    $html .= '</div>';
                }
                break;

            case 'langcorrectorder':
            case 'save_lang_corrected':
                $html .= '<div class="ecr_menu_box">';
                $html .= $this->drawLangSelector($sel_language, 'langcorrectorder');
                $html .= '  </div>';

                if($sel_language)
                {
                    $html .= '<div class="ecr_menu_box">';
                    $html .= JText::_('Cut');
                    $cut_after = JRequest::getInt('cut_after', 30);
                    $html .= '<select name="cut_after" onchange="submitbutton(\'langcorrectorder\');">';

                    for( $i=10; $i<62; $i = $i +2)
                    {
                        $selected =( $cut_after == $i ) ? ' selected="selected"' : '';
                        $html .= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>';
                    }//for

                    $html .= '</select>';
                    $html .= '</div>';
                    $html .= ecrHTML::chkVersioned();
                    $html .= '&nbsp;&nbsp;<span class="ecr_button img icon-16-save" onclick="submitbutton(\'save_lang_corrected\');" style="display: inline !important;">';
                    $html .= JText::_('Save');
                    $html .= '  </span>';
                }
                break;

            case 'langcorrectdeforder':
            case 'save_deflang_corrected':
                $html .= ecrHTML::chkVersioned();
                $html .= '<span class="ecr_button img icon-16-save"';
                $html .= 'onclick="submitbutton(\'save_deflang_corrected\');">'.JText::_('Save').'</span>';
                $html .= '<br /><br /><div class="explanation">'.JText::_('Drag and drop elements to rearrange. Add new comments.').'</div>';
                break;

            case 'show_versions':
            case 'show_version':
                $html .= '<div class="ecr_menu_box">';
                $html .= $this->drawLangSelector($sel_language, 'show_versions', true);
                $html .= '</div>';
                break;
                //            case 'convert':
                //                $html .= '<div class="ecr_menu_box">';
                //                $html .= $this->drawLangSelector($sel_language, 'convert', true);
                //                $html .= '</div>';
                //                break;

            case 'translate':
            case 'language_check':
            case 'languages':
            case 'convert':
                //--Do nothing
                break;

            default:
                echo 'UNDEFINED: '.$task;
                break;
        }//switch

        $html .= $htmlDescriptionDivs;

        if($ecr_help == 'all'
        || $ecr_help == 'some')
        {
            $html .= "<script type='text/javascript'>"
            ."window.addEvent('domready', function() {\n"
            ."function showTaskDesc(name) {\n"
            ."this.setStyle('display', 'block');\n"
            ."}\n"
            ."function hideTaskDesc(name) {\n"
            ."  this.setStyle('display', 'none');\n"
            ."}\n"
            . $jsVars
            . $jsEvents
            . "});\n"
            . "</script>";
        }

        return $html;
    }//function

    private function drawLangSelector($selected, $task, $showDefault=false)
    {
        $html = '';

        if(count( $this->project->langs) > 1
        || $showDefault)
        {
            $html .= NL.JText::_('Language').':&nbsp;';
            $html .= '<select name="sel_language" onchange="submitbutton(\''.$task.'\');">';
            $html .= '<option value="">'.JText::_('Choose').'</option>';

            foreach ($this->project->langs as $lang=>$scopes)
            {
                if($lang == 'en-GB' && ! $showDefault)
                {
                    //--default language ordered separated
                    continue;
                }

                $sSelected =($lang == $selected) ? ' selected="selected"' : '';
                $html .= '<option value="'.$lang.'" '.$sSelected.'>'.$lang.'</option>';
            }//foreach

            $html .= '</select>';
        }

        return $html;
    }//function

    protected function menuBox($task, $title)
    {
        $checked =($this->options->get($task)) ? ' checked="checked"' : '';

        $html = '';
        $html .= '<div class="ecr_menu_box" style="background-color: #ccc; margin-left: 0.3em;">';
        $html .= '<input type="checkbox" id="'.$task.'" name="options['.$task.']" onclick="submitform(\'convert\');" '.$checked.'" />';
        $html .= '<label for="'.$task.'">'.$title.'</label>';
        $html .= '</div>';

        return $html;;
    }//function

}//class
